package com.jwdf.uda.ui.fragment.user.register;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.bean.UploadImageResponse;
import com.jwdf.uda.databinding.FragmentUpdateInfoBinding;
import com.jwdf.uda.event.ImageSelectorEvent;
import com.jwdf.uda.event.UserEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UpdateDeviceInfo;
import com.jwdf.uda.http.action.UploadImageAction;
import com.jwdf.uda.http.action.UserUpdateInfoAction;
import com.jwdf.uda.photopicker.PhotoPickerActivity;
import com.jwdf.uda.runtime.PermissionRequest;
import com.jwdf.uda.runtime.RuntimePermission;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.ui.fragment.user.bean.UserSession;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ToastUtils;
import com.jwdf.uda.utils.UdaUtils;
import com.jwdf.uda.view.dialog.AlertDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import java.io.File;
import java.util.ArrayList;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/30.
 */
public class UpdateInfoFragment extends BaseFragment {
    private static final int REQ_AVATAR_CHANGE = 0x100;
    private static final int REQ_AVATAR_CROP = 0x101;
    private FragmentUpdateInfoBinding mDataBinding;
    private PbBean.PbSignUserSex mUsrSeX = PbBean.PbSignUserSex.USER_SEX_MAN;
    public View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (R.id.btn_comlete_info == v.getId()) {
                UdaUtils.hideInputMethod(v.getContext(), v);
                mDataBinding.ivClearInput.setVisibility(View.GONE);
                String nickName = mDataBinding.inputEditNickName.getText().toString().trim();
                if (TextUtils.isEmpty(nickName)) {
                    ToastUtils.show(getContext(), getString(R.string.user_can_not_be_null));
                    return;
                }
                Button btn = (Button) v;
                String newAvatar = (String) btn.getTag(R.id.tag_url);
                if (!TextUtils.isEmpty(newAvatar)) {
                    doUploadImageAction(nickName, newAvatar);
                } else {
                    updateUserInfo(nickName);
                }
            } else if (R.id.iv_clear_input == v.getId()) {
                mDataBinding.inputEditNickName.setText("");
            } else if (R.id.tv_change_avatar == v.getId()) {
                String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
                if (RuntimePermission.hasPermissions(getContext(), perms)) {
                    PhotoPickerActivity.startActivity(getContext(), REQ_AVATAR_CHANGE, new ArrayList<String>(), 1);
                } else {
                    showAlertNotice();
                }
            }
        }
    };
    private Uri imageUri;
    private RadioGroup.OnCheckedChangeListener mOnCheckChangerListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (R.id.radio_group_sex == group.getId()) {
                RadioButton rbSex = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
                String checkedItem = rbSex.getText().toString();
                mUsrSeX = getString(R.string.usr_sex_male).equals(checkedItem) ? PbBean.PbSignUserSex.USER_SEX_MAN : PbBean.PbSignUserSex.USER_SEX_WOMAN;
                //                mClothingStyle = getString(R.string.usr_sex_male).equals(checkedItem) ? PbBean.PbSignUserClothingStyle.USER_CLOTHING_STYLE_MAN : PbBean
                // .PbSignUserClothingStyle.USER_CLOTHING_STYLE_WOMAN;
                //                mSexOrientation = getString(R.string.usr_sex_male).equals(checkedItem) ? PbBean.PbSignUserSexOrientation.USER_SEX_ORIENTATION_LIKE_MAN : PbBean
                // .PbSignUserSexOrientation.USER_SEX_ORIENTATION_LIKE_WOMAN;
            }
            //            else if (R.id.radio_group_dress_style == group.getId()) {
            //                RadioButton rbStyle = (RadioButton) group.findViewById(group.getCheckedRadioButtonId());
            //                String checkedItem = rbStyle.getText().toString();
            //                if (getString(R.string.usr_style_male).equals(checkedItem)) {
            //                    mClothingStyle = PbBean.PbSignUserClothingStyle.USER_CLOTHING_STYLE_MAN;
            //                } else if (getString(R.string.usr_style_female).equals(checkedItem)) {
            //                    mClothingStyle = PbBean.PbSignUserClothingStyle.USER_CLOTHING_STYLE_WOMAN;
            //                } else if (getString(R.string.usr_style_normal).equals(checkedItem)) {
            //                    mClothingStyle = PbBean.PbSignUserClothingStyle.USER_CLOTHING_STYLE_MIDDLE;
            //                }
            //            }
        }
    };
    private TextWatcher mTextChangeListener = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //mDataBinding.inputEditNickName.setSelection(s.length());
        }

        @Override
        public void afterTextChanged(Editable s) {
            mDataBinding.ivClearInput.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
    }

    @Override
    public void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    public void onEvent(ImageSelectorEvent event) {
        if (ImageSelectorEvent.EVENT_ADD == event.getType() && event.getCode() == REQ_AVATAR_CHANGE) {
            startPhotoZoom(Uri.parse(event.getImages().get(0)));
        }
    }

    public void startPhotoZoom(Uri uri) {
        imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/avatartemp" + System.currentTimeMillis() + ".jpg"));
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//图像输出
        intent.putExtra("outputFormat",
                Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);//回调方法data.getExtras().getParcelable("data")返回数据为空
        startActivityForResult(intent, REQ_AVATAR_CROP);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 截图后返回
        if (requestCode == REQ_AVATAR_CROP && data != null) {
            ImageLoader.getInstance().displayImage(imageUri.toString(), mDataBinding.ivAvatar);
            mDataBinding.btnComleteInfo.setTag(R.id.tag_url, imageUri.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mDataBinding = FragmentUpdateInfoBinding.inflate(inflater, container, false);
        initViews();
        return mDataBinding.getRoot();
    }

    private void initViews() {
        checkPermission();
        mDataBinding.btnComleteInfo.setOnClickListener(mClickListener);
        mDataBinding.radioGroupSex.setOnCheckedChangeListener(mOnCheckChangerListener);
        //        mDataBinding.radioGroupDressStyle.setOnCheckedChangeListener(mOnCheckChangerListener);
        mDataBinding.inputEditNickName.addTextChangedListener(mTextChangeListener);
        mDataBinding.ivClearPasswdInput.setOnClickListener(mClickListener);
        ImageLoader.getInstance().displayImage(getArguments().getString("avatar_url",""), mDataBinding.ivAvatar);
        mDataBinding.tvChangeAvatar.setPaintFlags(mDataBinding.tvChangeAvatar.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        mDataBinding.tvChangeAvatar.setMovementMethod(LinkMovementMethod.getInstance());
        mDataBinding.tvChangeAvatar.setOnClickListener(mClickListener);
    }

    @PermissionRequest(100)
    private void checkPermission() {
        String perms[] = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (!RuntimePermission.hasPermissions(getContext(), perms)) {
            RuntimePermission.requestPermissions(this, getString(R.string.app_name), 100, perms);
        }
    }

    private void doUploadImageAction(final String nickName, final String image) {
        showProgressDialog();
        UploadImageAction action = new UploadImageAction(getContext(), image);
        onNewRequestCall(action.request(new UploadImageAction.IResCallback<String>() {
            @Override
            public void onCallback(int resultCode, UploadImageResponse response) {
                if (getView() != null) {
                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, response, getString(R.string.error_operation))) {
                        cancelRequest();
                        return;
                    }

//                    FileUtils.deleteTempFile(image);
                    updateUserInfo(nickName, response.getToken());
                }
            }
        }));

    }

    private void updateUserInfo(String nickName, String imageToken) {
        showProgressDialog();
        onNewRequestCall(UserUpdateInfoAction.newInstance(getContext(), nickName, imageToken, mUsrSeX).request(new AHttpService.IResCallback<PbBean.PbResUserUpdateInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserUpdateInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    PbBean.PbResUserUpdateInfo userLogin = response.body();
                    if (userLogin != null) {
                        UserSession userSession = new UserSession(ConfigUtils.getSessionId(getContext()), ConfigUtils.getToken(getContext()));
                        userSession.setUserId(userLogin.getUserInfo().getUserId());
                        userSession.setStylist(userLogin.getUserInfo().getIsDesigner());
                        userSession.setUCoin(userLogin.getUserInfo().getMoney());
                        userSession.setUserName(userLogin.getUserInfo().getUsername());
                        ConfigUtils.setCurrentUser(getContext(), userSession);
                        if (!ConfigUtils.isRejectPrivacyPermission(getContext())) {
                            reportDeviceInfo(getContext());
                        } else {
                            UserEvent event = new UserEvent();
                            event.setEvent(UserEvent.EVENT_STEP_4);
                            EventBusUtil.post(event);
                        }
                    }
                }
            }
        }));
    }

    private void reportDeviceInfo(final Context context) {
        PushAgent.getInstance(context).enable(new IUmengRegisterCallback() {
            @Override
            public void onRegistered(final String deviceToken) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        onNewRequestCall(UpdateDeviceInfo.newInstance(context, deviceToken).request(new AHttpService.IResCallback<PbBean.PbResSystemUpdateDeviceInfo>() {
                            @Override
                            public void onCallback(int resultCode, Response<PbBean.PbResSystemUpdateDeviceInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                                if (getView() != null) {
                                    if (response != null) {
                                        if (HttpHelper.showError(context, resultCode, baseServerInfo, getString(R.string.error_net))) {
                                            return;
                                        }
                                        PbBean.PbResSystemUpdateDeviceInfo deviceInfo = response.body();
                                        if (deviceInfo != null) {
                                            ConfigUtils.setPageLength(context, deviceInfo.getPageLength());
                                            ConfigUtils.setAboutPage(context, deviceInfo.getAboutPage());
                                            ConfigUtils.setUserProtocol(context, deviceInfo.getUserProtocolPage());
                                        }
                                    }
                                    UserEvent event = new UserEvent();
                                    event.setEvent(UserEvent.EVENT_STEP_4);
                                    EventBusUtil.post(event);
                                }
                            }
                        }));
                    }
                });
            }
        });
    }

    private void updateUserInfo(String nickName) {
        showProgressDialog();
        onNewRequestCall(UserUpdateInfoAction.newInstance(getContext(), nickName, mUsrSeX).request(new AHttpService.IResCallback<PbBean.PbResUserUpdateInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserUpdateInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    PbBean.PbResUserUpdateInfo userLogin = response.body();
                    if (userLogin != null) {
                        UserSession userSession = new UserSession(ConfigUtils.getSessionId(getContext()), ConfigUtils.getToken(getContext()));
                        userSession.setUserId(userLogin.getUserInfo().getUserId());
                        userSession.setStylist(userLogin.getUserInfo().getIsDesigner());
                        userSession.setUCoin(userLogin.getUserInfo().getMoney());
                        userSession.setUserName(userLogin.getUserInfo().getUsername());
                        ConfigUtils.setCurrentUser(getContext(), userSession);
                        if (!ConfigUtils.isRejectPrivacyPermission(getContext())) {
                            reportDeviceInfo(getContext());
                        } else {
                            UserEvent event = new UserEvent();
                            event.setEvent(UserEvent.EVENT_STEP_4);
                            EventBusUtil.post(event);
                        }
                    }
                }
            }
        }));
    }

    private void showAlertNotice() {
        final AlertDialog alertDialog = new AlertDialog(getContext(), getContext().getString(R.string.permission_denied_msg), new AlertDialog.CallbackListener() {
            @Override
            public void clickYes() {

            }
        });
        alertDialog.show();
    }
}
